<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;

/**
 * 视频审核管理
 *
 * @icon fa fa-video-camera
 */
class VideoAudit extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->view->assign("statusList", [
            0 => '待审核',
            1 => '已通过',
            2 => '已拒绝'
        ]);
        
        // 设置表格配置
        $this->assignconfig('table', [
            'columns' => [
                'id' => ['title' => 'ID', 'width' => '80px'],
                'report_id' => ['title' => '报工ID', 'width' => '100px'],
                'video_url' => ['title' => '视频URL', 'width' => '200px'],
                'upload_user_id' => ['title' => '上传用户', 'width' => '100px'],
                'status' => ['title' => '审核状态', 'width' => '100px', 'formatter' => 'status'],
                'audit_user_id' => ['title' => '审核人', 'width' => '100px'],
                'audit_time' => ['title' => '审核时间', 'width' => '150px', 'formatter' => 'datetime'],
                'audit_reason' => ['title' => '审核原因', 'width' => '200px'],
                'createtime' => ['title' => '上传时间', 'width' => '150px', 'formatter' => 'datetime'],
                'operate' => ['title' => '操作', 'width' => '200px', 'formatter' => 'operate']
            ],
            'operate' => [
                'audit' => [
                    'title' => '审核',
                    'icon' => 'fa fa-check',
                    'class' => 'btn btn-xs btn-success',
                    'url' => 'audit_page',
                    'params' => ['ids' => '{ids}']
                ],
                'reject' => [
                    'title' => '拒绝',
                    'icon' => 'fa fa-times',
                    'class' => 'btn btn-xs btn-danger',
                    'url' => 'audit_page',
                    'params' => ['ids' => '{ids}', 'status' => '2']
                ],
                'view' => [
                    'title' => '查看',
                    'icon' => 'fa fa-eye',
                    'class' => 'btn btn-xs btn-info',
                    'url' => 'view'
                ],
                'del' => [
                    'title' => '删除',
                    'icon' => 'fa fa-trash',
                    'class' => 'btn btn-xs btn-danger',
                    'url' => 'del'
                ]
            ]
        ]);
    }

    /**
     * 视频审核列表
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 查询视频审核记录
            $list = Db::name('scanwork_audit_video')
                ->alias('av')
                ->join('scanwork_report r', 'av.report_id = r.id')
                ->join('user u', 'av.upload_user_id = u.id')
                ->join('user au', 'av.audit_user_id = au.id', 'LEFT')
                ->field('av.*, r.allocation_id, u.nickname as upload_user_name, au.nickname as audit_user_name')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
                
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核页面
     */
    public function audit_page()
    {
        $ids = $this->request->get('ids');
        $status = $this->request->get('status', '1'); // 默认通过
        
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $idsArr = is_array($ids) ? $ids : explode(',', $ids);
        
        // 获取视频信息
        $videos = Db::name('scanwork_audit_video')
            ->alias('av')
            ->join('scanwork_report r', 'av.report_id = r.id')
            ->join('user u', 'av.upload_user_id = u.id')
            ->field('av.*, r.allocation_id, u.nickname as upload_user_name')
            ->where('av.id', 'in', $idsArr)
            ->select();
        
        $this->view->assign('videos', $videos);
        $this->view->assign('ids', $ids);
        $this->view->assign('status', $status);
        
        return $this->view->fetch();
    }

    /**
     * 审核视频
     */
    public function audit()
    {
        $ids = $this->request->post('ids');
        $status = $this->request->post('status');
        $reason = $this->request->post('audit_reason', '');
        
        if (!$ids || !in_array($status, ['1', '2'])) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        $idsArr = is_array($ids) ? $ids : explode(',', $ids);
        $success = 0;
        $fail = 0;
        
        foreach ($idsArr as $id) {
            try {
                $updateData = [
                    'status' => $status,
                    'audit_user_id' => $this->auth->id,
                    'audit_time' => time()
                ];
                
                if ($status == '2' && $reason) {
                    $updateData['audit_reason'] = $reason;
                }
                
                $result = Db::name('scanwork_audit_video')
                    ->where('id', $id)
                    ->update($updateData);
                
                if ($result) {
                    $success++;
                } else {
                    $fail++;
                }
            } catch (\Exception $e) {
                $fail++;
            }
        }
        
        if ($success > 0) {
            return json(['code' => 1, 'msg' => "审核成功：{$success} 条，失败：{$fail} 条"]);
        } else {
            return json(['code' => 0, 'msg' => '审核失败']);
        }
    }

    /**
     * 查看视频详情
     */
    public function view($ids = null)
    {
        $row = Db::name('scanwork_audit_video')
            ->alias('av')
            ->join('scanwork_report r', 'av.report_id = r.id')
            ->join('user u', 'av.upload_user_id = u.id')
            ->join('user au', 'av.audit_user_id = au.id', 'LEFT')
            ->field('av.*, r.allocation_id, u.nickname as upload_user_name, au.nickname as audit_user_name')
            ->where('av.id', $ids)
            ->find();
            
        if (!$row) {
            $this->error('视频记录不存在');
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 删除视频
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 批量审核
     */
    public function batchAudit()
    {
        $ids = $this->request->post('ids');
        $status = $this->request->post('status');
        $reason = $this->request->post('audit_reason', '');
        
        if (!$ids || !in_array($status, ['1', '2'])) {
            $this->error('参数错误');
        }
        
        $idsArr = is_array($ids) ? $ids : explode(',', $ids);
        $success = 0;
        $fail = 0;
        
        Db::startTrans();
        try {
            foreach ($idsArr as $id) {
                $updateData = [
                    'status' => $status,
                    'audit_user_id' => $this->auth->id,
                    'audit_time' => time()
                ];
                
                if ($status == '2' && $reason) {
                    $updateData['audit_reason'] = $reason;
                }
                
                $result = Db::name('scanwork_audit_video')
                    ->where('id', $id)
                    ->update($updateData);
                
                if ($result) {
                    $success++;
                } else {
                    $fail++;
                }
            }
            
            Db::commit();
            $this->success("批量审核完成：成功 {$success} 条，失败 {$fail} 条");
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('批量审核失败：' . $e->getMessage());
        }
    }

    /**
     * 获取视频统计
     */
    public function getStats()
    {
        $stats = [
            'total' => Db::name('scanwork_audit_video')->count(),
            'pending' => Db::name('scanwork_audit_video')->where('status', 0)->count(),
            'approved' => Db::name('scanwork_audit_video')->where('status', 1)->count(),
            'rejected' => Db::name('scanwork_audit_video')->where('status', 2)->count()
        ];
        
        $this->success('获取成功', $stats);
    }
}
